package com.bfl.sa.personal.message.service;

import com.bfl.sa.common.service.BaseService;
import com.bfl.sa.common.utils.CollectionUtils;
import com.bfl.sa.common.utils.DateUtils;
import com.bfl.sa.personal.message.entity.Message;
import com.bfl.sa.personal.message.entity.MessageContent;
import com.bfl.sa.personal.message.entity.MessageState;
import com.bfl.sa.personal.message.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;


@Service
public class MessageService extends BaseService<Message, Long> {

    @Resource
    private MessageMapper messageMapper;

    /**
     * 改变发件人 消息的原状态为目标状态
     */
    public Integer changeSenderState(Long senderId, MessageState oldState, MessageState newState) {
        Date changeDate = new Date();
        return messageMapper.changeSenderState(senderId, oldState, newState, changeDate);
    }

    /**
     * 改变收件人人 消息的原状态为目标状态
     */
    public Integer changeReceiverState(Long receiverId, MessageState oldState, MessageState newState) {
        Date changeDate = new Date();
        return messageMapper.changeReceiverState(receiverId, oldState, newState, changeDate);
    }

    /**
     * 物理删除那些已删除的（即收件人和发件人 同时都删除了的）
     */
    public Integer clearDeletedMessage(MessageState deletedState) {
        return messageMapper.clearDeletedMessage(deletedState);
    }

    /**
     * 更改状态
     * @param expireDays 当前时间-过期天数 时间之前的消息将改变状态
     */
    public Integer changeState(ArrayList<MessageState> oldStates, MessageState newState, int expireDays) {
        Date changeDate = new Date();
        Integer count = messageMapper.changeSenderStates(oldStates, newState, changeDate, DateUtils.addDays(changeDate, -expireDays));
        count += messageMapper.changeReceiverStates(oldStates, newState, changeDate, DateUtils.addDays(changeDate, -expireDays));
        return count;
    }

    /**
     * 统计用户收件箱未读消息
     */
    public Long countUnread(Long userId) {
        return messageMapper.countUnread(userId, MessageState.in_box);
    }

    public void markRead(final Long userId, final Long[] ids) {
        if(CollectionUtils.isEmpty(ids)) {
            return;
        }
        messageMapper.markRead(userId, Arrays.asList(ids));
    }

    public void saveContent(Long messageId, MessageContent content) {
        messageMapper.insertContent(messageId, content);
    }
}
